package STUDIO.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import STUDIO.excepcion.DAOStudioExcepcion;
import STUDIO.modelo.reserva;
import STUDIO.util.CONEXIONStudioBD;


public class Reserva_SalaDAO extends BaseStudioDAO {

	public reserva insertar(reserva vo) throws DAOStudioExcepcion {

		System.out.println("Reserva_SalaDAO: generar()");
		String query = "INSERT INTO reserva_sala (armado_sala_id_armado,cliente_idcliente) VALUES (?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

		try {
			con = CONEXIONStudioBD.obtenerConexion();
			//con.setAutoCommit(false);
			stmt = con.prepareStatement(query);
			stmt.setInt(1, vo.getArmado_sala().getId_armado());
			stmt.setInt(2, vo.getClientes().getIdCliente());
			System.out.println(query);
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar reserva_sala");
			}

			int idr = 0;
			//se hace para saber el ultimo id
			query = "SELECT LAST_INSERT_ID()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				idr = rs.getInt(1);
			}
			vo.setId_reserva_sala(idr);
			//
			//con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				throw new DAOStudioExcepcion(e.getMessage());
			}
			System.err.println(e.getMessage());
			throw new DAOStudioExcepcion(e.getMessage());
		} finally {
			try {
				con.setAutoCommit(true);
			} catch (SQLException e) {
				throw new DAOStudioExcepcion(e.getMessage());
			}
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

}
